package com.tarena.lbs.article.web.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.article.web.repository.ArticleCategoryRepository;
import com.tarena.lbs.article.web.repository.ArticleESRepository;
import com.tarena.lbs.article.web.repository.ArticleRepository;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.content.utils.SequenceGenerator;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.po.ArticleCategoryPO;
import com.tarena.lbs.pojo.content.entity.ArticleSearchEntity;
import com.tarena.lbs.pojo.content.param.ArticleContentParam;
import com.tarena.lbs.pojo.content.query.ArticleQuery;
import com.tarena.lbs.pojo.content.vo.ArticleCategoryVO;
import com.tarena.lbs.pojo.content.vo.ArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArticleService {
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ArticleCategoryRepository categoryRepository;
    @Autowired
    private ArticleESRepository articleESRepository;
    public PageResult<ArticleVO> articlePages(ArticleQuery query) throws BusinessException {
        //1. 取一下query的source数据 做分支判断
        Integer source = query.getSource();
        //1 2 查询条件和逻辑不同 1 需要地理位置 esrepository干不了必须使用client 解析创建userId
        PageResult<ArticleVO> voPages=new PageResult<>();
        //补充 重新构造入参query参数 根据不同业务封装不同数据;
        ArticleQuery serviceQuery=new ArticleQuery();
        serviceQuery.setPageNo(query.getPageNo()!=null?1: query.getPageNo());
        serviceQuery.setPageSize(query.getPageSize());
        if (source==1){
            serviceQuery.setLatitude(query.getLatitude());
            serviceQuery.setLongitude(query.getLongitude());
            serviceQuery.setArticleLabel(query.getArticleLabel());
            //前台只查询上线的文章 UNDO
        }else{
            UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
            Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证失败"));
            serviceQuery.setUserId(userPrinciple.getId());
            serviceQuery.setSource(2);
            serviceQuery.setArticleStatus(query.getArticleStatus());
            serviceQuery.setArticleTitle(query.getArticleTitle());
            serviceQuery.setUpdateEndTime(query.getUpdateEndTime());
            serviceQuery.setUpdateStartTime(query.getUpdateStartTime());
        }
        //仓储层查询 要复用 非空属性条件拼接
        //使用esRepository可以的 searchSimilar 给一个userId 创建文章作者
        PageResult<ArticleSearchEntity> entityPages=articleRepository.getEntityPages(serviceQuery);
        //将仓储层解析的数据封装成VO
        voPages.setPageNo(query.getPageNo());
        voPages.setPageSize(query.getPageSize());
        voPages.setTotal(entityPages.getTotal());
        List<ArticleVO> vos=null;
        if (entityPages.getTotal()>0){
            vos=entityPages.getObjects().stream().map(entity->{
                ArticleVO vo=new ArticleVO();
                BeanUtils.copyProperties(entity,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPages.setObjects(vos);
        return voPages;
    }
    public PageResult<ArticleCategoryVO> categoryPages(ArticleQuery query) {
        //让仓储层给返回list
        List<ArticleCategoryPO> pos=categoryRepository.getCategoryList(query);
        PageResult<ArticleCategoryVO> voPages=new PageResult<>();
        voPages.setPageNo(query.getPageNo());
        voPages.setPageSize(query.getPageSize());
        voPages.setTotal(10L);
        List<ArticleCategoryVO> vos=pos.stream().map(po->{
            ArticleCategoryVO vo=new ArticleCategoryVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }).collect(Collectors.toList());
        voPages.setObjects(vos);
        return voPages;
    }

    public void articleAdd(ArticleContentParam param) throws BusinessException {
        //1.认证数据拿到 没有抛异常
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","认证用户失败"));
        //2.封装 copy
        ArticleSearchEntity entity=new ArticleSearchEntity();
        BeanUtils.copyProperties(param,entity);
        //3.补全entity docId userId time location status
        entity.setId(SequenceGenerator.sequence());
        entity.setUserId(userPrinciple.getId());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(entity.getCreateTime());
        entity.setLocation(param.getLatitude()+","+param.getLongitude());
        entity.setArticleStatus(1);
        entity.setFavoriteCount(0);
        entity.setLikeCount(0);
        entity.setAccessCount(0);
        entity.setArticleUsername(userPrinciple.getNickname());
        log.info("articleAdd entity:{}",entity);

        //4.将entity写入es索引
        articleESRepository.save(entity);
    }

    public HashSet<String> articleLabels(ArticleQuery articleQuery) throws IOException {
        //1.将参数交给仓储层 查询并且去重返回文章对象
        List<ArticleSearchEntity> entities=articleRepository.getArticleLabelsOnLocation(articleQuery);
        //2.业务不需要文章数据 标题 内容 等 去重之后只需要获取里面标签
        HashSet<String> labels=new HashSet<>();
        if (CollectionUtils.isNotEmpty(entities)){
            for (ArticleSearchEntity entity : entities) {
                labels.add(entity.getArticleLabel());
            }
        }
        return labels;
    }

    public ArticleVO articleDetail(String id) {
        ArticleSearchEntity articleSearchEntity = articleESRepository.findById(Integer.valueOf(id)).get();
        ArticleVO vo=new ArticleVO();
        if (articleSearchEntity!=null){
            BeanUtils.copyProperties(articleSearchEntity,vo);
        }
        return vo;
    }
}











